<?php

class RotatingAdsController extends AppController {
  public $helpers = array('Html', 'TWSForm', 'Paginator');
  public $components = array('Session', 'Util', 'Upload');
  public $name = 'RotatingAds';
  public $paginate;


  function __construct($request=null, $response=null) {
    parent::__construct($request, $response);
    $this->paginate = array(
        'limit' => Configure::read('App.pageResultLimit'),
        'order' => array(
            'RotatingAd.start_date' => 'desc', 'RotatingAd.end_date'=>'desc'
            ));
  }

  function index($adId = null) {
    if (empty($adId)){
      throw new NotFoundException();
    }
      $opts = array(
            'fields'=>array('RotatingAd.id','RotatingAd.ad_location','RotatingAd.description','RotatingAd.ad_text','RotatingAd.image_path','RotatingAd.start_date','RotatingAd.end_date'),
            'conditions'=>array('RotatingAd.id'=>$adId,'RotatingAd.start_date <= Now()','RotatingAd.end_date >= Now()')
      );
      $ads = $this->RotatingAd->find('all',$opts);
      $this->set('adInfo',$ads);
  }

    //admin
  function admin_index() {
    $this->layout="admin";
    $this->set('ads', $this->paginate('RotatingAd'));
  }

  function admin_add() {
    $this->layout = "admin";
    $this->set('options', Configure::read("App.rotatingAdsLocations"));
    $test = $this->RotatingAd->validate;
    if ($this->request->is('post')) {
      $this->_processAction($this->request, 'add');
    }
  }
    //admin
  function admin_edit($id = null) {
    $this->layout="admin";
    $this->set('options', Configure::read("App.rotatingAdsLocations"));
    $this->RotatingAd->id = $id;
    if ($this->request->is('get')) {
      $this->request->data = $this->RotatingAd->read();
      $this->request->data['RotatingAd']['start_date'] = $this->Util->formatDate($this->request->data['RotatingAd']['start_date'], true);
      $this->request->data['RotatingAd']['end_date'] = $this->Util->formatDate($this->request->data['RotatingAd']['end_date'], true);
    } else {
      //check for delete ad
      if (isset($this->request->data['deleteBtn'])) {
        $this->admin_delete($id);
      } else {
        $this->_processAction($this->request, 'edit', $id);
      }
    }
  }

  public function servicesAds() {
    $ads = $this->Session->read('ServicesRotatingAds');
    if (empty($ads)) {
      try {
      $adList1 = $this->RotatingAd->find("all", array("conditions"=>array('RotatingAd.ad_location'=>'ServicesPage1','RotatingAd.start_date <= Now()','RotatingAd.end_date >= Now()'),"order" => array('RotatingAd.start_date' => 'desc', 'RotatingAd.end_date'=>'desc')));
      $adList2 = $this->RotatingAd->find("all", array("conditions"=>array('RotatingAd.ad_location'=>'ServicesPage2','RotatingAd.start_date <= Now()','RotatingAd.end_date >= Now()'),"order" => array('RotatingAd.start_date' => 'desc', 'RotatingAd.end_date'=>'desc')));
      $ads = array("list1"=>$adList1,"list2"=>$adList2);
    } catch (Exception $e){
      CakeLog::write(LOG_ERROR, $e->getMessage());
    }
      $this->Session->write('ServicesRotatingAds',$ads);
    }
    return $ads;
  }

    private function _processAction($dataIn, $action='add', $id=null) {
      $data = $this->_processRequestData($dataIn);
      $this->RotatingAd->set($data);
      if ($this->RotatingAd->validates()) {
        $data["RotatingAd"]["start_date"] = $this->Util->formatDate($data["RotatingAd"]["ad_start_date"]);
        $data["RotatingAd"]["end_date"] = $this->Util->formatDate($data["RotatingAd"]["ad_end_date"]);
        $data["RotatingAd"]["ad_location"]= $data["RotatingAd"]["ad_ad_location"];
        $data["RotatingAd"]["description"]= $data["RotatingAd"]["ad_description"];
        $data["RotatingAd"]["ad_text"]= $data["RotatingAd"]["ad_ad_text"];

        if (!empty($data["RotatingAd"]["ad_image_path"]) && !empty($data["RotatingAd"]["ad_image_path"]['name'])) {
          $imageUploaded = $this->Upload->uploadImage($data["RotatingAd"]["ad_image_path"], WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' .Configure::read('App.rotatingAdsImageFolder'),Configure::read('App.rotatingAdsImageWidth') );
          $data["RotatingAd"]["image_path"] = Configure::read('App.rotatingAdsImageFolder') . '/' . $imageUploaded;
        } else {
          if($action==='add') {
            $data["RotatingAd"]["image_path"] = null;
          } else {
            $data["RotatingAd"]["image_path"] = isset($data["RotatingAd"]["_ad_image_path"]) ? $data["RotatingAd"]["_ad_image_path"] : null;
          }
        }
        if ($this->RotatingAd->save($data, false)) {
          $this->Session->setFlash('The record was successfully saved.');
          $this->redirect(array('action' => 'index'));
        }
      } else {
        if($action!=='add') {
          //getting previous image
          $data['RotatingAd']['image_path']=$data["RotatingAd"]["_ad_image_path"];
          $data['RotatingAd']['id']=$id;
        }
        $this->request->data['RotatingAd'] = $data['RotatingAd'];
        $this->set('errors', $this->RotatingAd->validationErrors);
      }
      if($action==='add') {
        $this->render('admin_add');
      } else {
        $this->render('admin_edit');
      }
  }

  //admin
  function admin_delete($id) {
    $this->layout="admin";
    $this->admin_deleteImage($id, false);
    if ($this->RotatingAd->delete($id)) {
      $this->Session->setFlash('The record has been deleted.');
      $this->redirect(array('action' => 'index'));
    }
  }

  //admin
  function admin_deleteImage($id, $redirect=true) {
    $this->layout="admin";
    $image = $this->RotatingAd->read('image_path', $id);
    $imagePath = $image['RotatingAd']['image_path'];
    if (!empty($imagePath)) {
      $result = $this->Util->deleteFile(WWW_ROOT . '/' . Configure::read('App.imageFolder') . '/' . $imagePath);
      $this->RotatingAd->save(array('RotatingAd' => array('id' => $id, 'image_path' => '')), false, array('image_path'));
      if($redirect){
        $this->Session->setFlash('The image has been deleted.');
        $this->redirect(array('action' => 'edit', $id));
      }
    }
  }
}

?>
